<?php

namespace Buu\Modules\Domain\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\excel\DownExcel;
use Doraemon\cache\Queue;
use Doraemon\tools\PointConfig;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Form\NestedForm;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\model\DomainConfig\DomainName;
use Doraemon\model\DomainConfig\TemplateHost;
use Encore\Admin\Widgets\Table;




class DomainConfigController extends Controller
{

    const NORMAL_WORD = '/home/adm_rsync_dir/article_common_remark.txt';

    public function __construct(Request $request)
    {
        parent::__construct();

    }


    public function index(Request $request, Content $content)
    {
        Admin::script($this->setScript());
        $requestParams = $request->all();
        $condition = [];
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition=[
            'domain_status'=> [DomainName::STATUS_NORMAL , DomainName::STATUS_ONLINE]
        ];
        if($requestParams['domain_name']){
            $condition['domain_name[~]'] = $requestParams['domain_name'];
        }

        if($requestParams['template_id']){
            $condition['template_id'] = $requestParams['template_id'];
        }
        $total = DomainName::getCountByWhere($condition);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $condition['ORDER'] = ['id' => 'DESC'];
        $list = DomainName::getListByWhere($condition);
        $templateList = TemplateHost::selectByWhere(['template_status' => [TemplateHost::STATUS_NORMAL]]);
        $info = [];
        $template_info = [];
        if($templateList && is_array($templateList)){
            $templateList = array_combine(array_column($templateList,'id') , $templateList);
            $template_info = array_combine(array_column($templateList,'id') , array_column($templateList,'template_name'));

            foreach($templateList as $key=>$val ){
                $hashContent = json_decode($val['content'] , true);
                $id = $val['id'];
                $info['hashContent_'.$id] = $hashContent;
            }
        }
        if($list && is_array($list))
        {
            foreach($list as &$val){
                $val['host'] = 'host 内容';
                if($templateList[$val['template_id']]){
                    $val['template_name'] = $templateList[$val['template_id']]['template_name'];
                    $content_arr = json_decode($val['content'] , true);
                    $template_arr  = $info['hashContent_'.$val['template_id']];
                    $result = array_diff_assoc($content_arr, $template_arr);
                    $contentInfo = $content_arr;
                    foreach($template_arr as $key=>$temp)
                    {
                        $host= $temp;
                        if($result[$key]){
                            $host = $result[$key];
                        }
                        $contentInfo[$key] = $host;
                    }
                    $val['host_content'] = $contentInfo;
                }else{
                    $val['host_content'] = json_decode($templateList[$val['template_id']]['content'] , true)? : [];
                }

                }
        }


        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => $pageSize
        ]);
        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel ,$template_info) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                //筛选
                $grid->filter(function (\Encore\Admin\Grid\Filter $filter) use ($template_info){
                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1/2, function ($filter) {
                        $filter->dropDown('Find', [
                            'domain_name' => "名称",
                        ]);

                    });
                    $filter->column(1/2, function ($filter)use ($template_info) {
                        $filter->equal('template_id', '模版')->checkbox($template_info);

                    });

                });
                $grid->column("domain_name", '名称') ->display(function (){
                    $display  = [];
                    $display[] =  '<span>'.$this->domain_name.'</span>';
                    if($this->template_name){
                        $display[] =  '<span>'.$this->template_name.'</span>';
                    }
                    return implode('<br/>', $display);
                }) -> width(200);
                $grid->column("host", 'host内容')->modal('host列表', function ($model) {
                    $result = [];
                    $contentArr = $model['host_content'] ;
                    foreach ($contentArr as $key =>$val){
                        $result[]=[
                            'api' => $key,
                            'host' => $val ? :'无'
                        ];
                    }

                    return new Table(['Api项目', 'host'], $result);
                })->width(500);

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->append('<a href="/admin/domain/edit/' . $actions->row->id . '" class="fa fa-edit">编辑</a>');
                    //复制功能
                    $copyUrl =  '/admin/domain/copy/'.$actions->row->id;
                    $actions->append('<a class="fa fa-copy" href="' . $copyUrl . '">复制</a>');
                });

            });
        $tab = new Tab();
        $tab->addLink('模版列表', '/admin/domain/template/index');
        $tab->add('域名列表', $gridList->render() ,true);

        $content->row($tab);
        return $content
            ->header('域名列表')
            ->breadcrumb(['text' => '域名列表']);

    }

    /*创建栏目
  *
  * */
    public function create(Request $request, Content $content, $id = 0)
    {
        Admin::script('
                       $("tfoot").css("display" , "none");
                      $("input.form-control").attr("placeholder" ,"输入host");
                       $("input.domain_name").attr("placeholder" ,"输入名称");
        ');
        $header = '添加';
        if ($id) {
            $header = '编辑';
        }
        $info  = $id ? DomainName::getByWhere(['id' => $id] ) :[];

        $hash_template = [];
        $templateList  = TemplateHost::selectByWhere(['template_status' => TemplateHost::STATUS_NORMAL]) ? : [];
        if($templateList && is_array($templateList)){
            $templateInfo = array_combine(array_column($templateList,'id') , array_column($templateList,'template_name'));

           foreach($templateList as $key=>$val ){
               $hashContent = json_decode($val['content'] , true);
               $id = $val['id'];
               $hash_template[$id] =function (Form $form) use($id) {
                   $form->keyValue('hashContent_'.$id,'模版内容')->required();
               };
               $info['hashContent_'.$id] = $hashContent;
           }
            if($info['id']){
               $content_arr = json_decode($info['content'] , true);
               $template_arr  = $info['hashContent_'.$info['template_id']];
               $result = array_diff_assoc($content_arr, $template_arr);
               $contenthost =$content_arr;
               foreach($template_arr as $key=>$val)
               {
                   if($result[$key]){
                       $val = $result[$key];
                   }
                   $contenthost[$key] = $val;
               }
               $info['hashContent_'.$info['template_id']] = $contenthost;
               $info['template_name'] = $templateInfo[$info['template_id']];
            }
        }



        $form = new Form($info);
        $form->hidden('id');
        $form->text('domain_name', '名称')->required();

        if($info['id'] ) {
            $form ->hidden("template_id");
            $form ->text('template_name' ,'模版名称')->help("输入模版名称")->readonly();
            $form ->keyValue('hashContent_'.$info['template_id'] ,'host');

        }else{
            $form->fieldChange('template_id', '模版选择', $form)
                ->options($templateInfo)->required()
                ->callablePreCommon(function (Form $form) use($hash_template){
                })->callableMap($hash_template);

        }

        $form->action(url('admin/domain/save'));
        $content->row($form);
        return $content->header($header)->breadcrumb(
            ['text' => '模版列表', 'url' => url('admin/domain/index')],
            ['text' => $header]);
    }



    /*复制域名
    *
    * */
    public function copy(Request $request, Content $content, $id )
    {
        Admin::script('
                       $("tfoot").css("display" , "none");
                      $("input.form-control").attr("placeholder" ,"输入host");
                       $("input.domain_name").attr("placeholder" ,"输入名称");
        ');
        $info  = DomainName::getByWhere(['id' => $id] );
        $header = '复制'.$info['domain_name'];
        $hash_template = [];
        $templateList  = TemplateHost::selectByWhere(['template_status' => TemplateHost::STATUS_NORMAL]) ? : [];
        if($templateList && is_array($templateList)){
            $templateInfo = array_combine(array_column($templateList,'id') , array_column($templateList,'template_name'));

            foreach($templateList as $key=>$val ){
                $hashContent = json_decode($val['content'] , true);
                $id = $val['id'];
                $hash_template[$id] =function (Form $form) use($id) {
                    $form->keyValue('hashContent_'.$id,'模版内容')->required()->rules('required|max:5');
                    ;
                };
                $info['hashContent_'.$id] = $hashContent;
            }
            if($info && is_array($info)){
                $info['domain_name'] = $info['domain_name']."_copy";
                $content_arr = json_decode($info['content'] , true);
                $template_arr  = $info['hashContent_'.$info['template_id']];
                $result = array_diff_assoc($content_arr, $template_arr);

                foreach($template_arr as $key=>&$val)
                {
                    if($result[$key]){
                        $val = $result[$key];
                    }
                }
                $info['hashContent_'.$info['template_id']] = $template_arr;
                $info['template_name'] = $templateInfo[$info['template_id']];

            }
        }
        $form = new Form($info);
        $form->text('domain_name', '名称')->required();
        $form ->hidden("template_id");
        $form ->text('template_name' ,'模版名称')->readonly();
        $form ->keyValue('hashContent_'.$info['template_id'] ,'host');
//        $form->fieldChange('template_id', '模版选择', $form)
//            ->options($templateInfo)->required()
//            ->callablePreCommon(function (Form $form) use($hash_template){
//            })->callableMap($hash_template);
        $form->action(url('admin/domain/save'));
        $content->row($form);

        return $content->header($header)->breadcrumb(
            ['text' => '模版列表', 'url' => url('admin/domain/index')],
            ['text' => $header]);
    }

    /*添加成功
     *
     * */
    public function save(Request $request)
    {
        try {
            $params = $request->all();

            $id = isset($params['id']) ? $params['id'] : 0;

            if($params['template_id']){
                $templateInfo =  TemplateHost::getByWhere(['id' => $params['template_id']]);
            }
            if(empty($templateInfo)){
                throw new \Exception('选择模版不存在');
            }

            if (empty($params['hashContent_'.$params['template_id']])) {
                throw new \Exception('模版内容不能为空');
            }
            $templateList = $templateInfo['content']? json_decode($templateInfo['content'],true):[];
            $content_arr =  array_combine($params['hashContent_'.$params['template_id']]['keys'] ,$params['hashContent_'.$params['template_id']]['values'] );

            foreach($content_arr as $p => $val){
                if ($templateList[$p] === $val){
                    $content_arr[$p] = '';
                }
            }
            if( empty($content_arr)){
                throw new \Exception('模版内容输入不为json');
            }

            $data = [
                'content' => json_encode($content_arr),
                'domain_name' => $params['domain_name'],
                'domain_status'  => 1,
                'template_id' => (int)$params['template_id'] ?: 0,
                'admin_id' => Admin::user()->id,
            ];

            if($id){
                $result = DomainName::updateData($data , ['id' => $id]);
            }else{
                $result =  DomainName::insertData($data);
            }
            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            if ($result) {
                $url = url('/admin/domain/index');
                return redirect($url)->with(compact('success'));
            }

            $error = new MessageBag([
                'title' => '操作失败'
            ]);
            return back()->withInput()->with(compact('error'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }


    /**
     * 删除
     * @param $id
     * @return void
     */
    public function del(Request $request, $id)
    {
        DomainName::updateData(['domain_status' => DomainName::STATUS_DELETE] , ['id' => $id]);
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }


    /*删除精选
      * */
    public function updateTemplate(Request $request ,$id)
    {
        try{
            //删除精选
            $info = DomainName::getByWhere(['id' => $id]);
            if(empty($info)){
                throw new \Exception('内容不存在！');
            }
            $templateInfo = [];
            $content_arr = [];
            if($info['template_id']){
                $templateInfo = TemplateHost::getByWhere(['id' =>$info['template_id']]);
                $hostHash = $templateInfo['content'];
                $content = str_replace('*' , $info['domain_identify'] , $hostHash);
                $content_arr = json_decode($content  , true);
            }
            if(empty($templateInfo) || empty($content_arr)){
                throw new \Exception('模版不存在！');
            }
            $data =  [
                'host_content' => json_encode($content_arr),
                'domain_status'  => 1,
                'admin_id' => Admin::user()->id,
            ];
            $rs = DomainName::updateData($data , ['id' => $id]);
            if($rs){
                $status= true ;
                $message = "操作成功";
            }
        }catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
        }
        return  response()->json(compact('status', 'message'));
    }


    /*设置scirpt
  *
  * */
    private function setScript()
    {
        return <<<SCRIPT
       $('.updatetemplate').unbind('click').click(function(){
            var id= $(this).data('id');
            layer.confirm('确定要更新么？', {
                btn: ['确定', '取消']
            }, function (index) {
                layer.close(index);
                 let url = '/admin/domain/updateTemplate/'+ id;
                let params = {};
                $.post(url, params , function (result) {
                    if (result.status == 1) {
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            });
        });
SCRIPT;
    }

    /**
     * 编辑界面
     *
     * @param $id
     * @param Content $content
     * @return Content
     * @time 2022/10/20 16:27
     * @desc
     */
    public function edit($id, Content $content)
    {
        $info = $id ? DomainName::getByWhere(['id' => $id]) : [];
        $info['content'] = $info['content'] ? json_decode($info['content'], true) : [];
        $iTemplateId = $info['template_id'];

        $aTemp = TemplateHost::getByWhere([
            'id' => $iTemplateId,
            'template_status' => TemplateHost::STATUS_NORMAL
        ]) ?: [];
        $aTemp['content'] = $aTemp['content'] ? json_decode($aTemp['content'], true) : [];
        $info['template_name'] = $aTemp['template_name'];
        $form = new Form($info);
        $form->hidden("id");
        $form->text('domain_name', '名称')->required();
        $form->display('template_name', '模板');

        $form->embeds('host', function ($form) use ($aTemp, $info) {

            foreach ($info['content'] as $sPro => $sHost) {
                if (!$sHost) {
                    $p = $aTemp['content'][$sPro] ?: "无";
                    $form->text($sPro, $sPro)->placeholder("默认host：" . $p);
                } else {
                    $form->text($sPro, $sPro)->default($sHost);
                }
            }
        });
        $form->action('editSave');
        $content->row($form);
        return $content->header("创建")->breadcrumb(
            ['text' => '模版列表', 'url' => url('admin/domain/index')],
            ['text' => '创建']);
    }

    /**
     * 编辑保存
     *
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|null
     * @time 2022/10/20 16:27
     * @desc
     */
    public function editSave(Request $request)
    {
        try {
            $params = $request->all();
            $data['domain_name'] = $params['domain_name'];
            $id = $params['id'];
            $where['id'] = $id;
            $data['content'] = json_encode($params['host']);
            DomainName::updateData($data, $where);
            $success = new MessageBag([
                'title' => '成功',
            ]);

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }

        return redirect('/admin/domain/edit/' . $id)
            ->with(compact('success'));
    }











}